package com.作业.Day16;


import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.*;
import java.util.ArrayList;

/**
 * 将存有多个自定义对象的集合序列化操作，保存到list.txt文件中
 * 反序列化list.txt ,并遍历集合，打印对象信息
 */
public class Test1 {
    public static void main(String[] args) {
        //把若干个学生放到集合中
        ArrayList<Student> st = new ArrayList<>();
        st.add(new Student("小美","20"));
        st.add(new Student("小明","24"));
        st.add(new Student("小黄","29"));
        //进行序列化
        String name="Day16-h1,txt";
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(name));
             ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(name))
        )
        {
             objectOutputStream.writeObject(st);
            System.out.println("序列化成功");
        ArrayList<Student> arrayList = (ArrayList<Student>) objectInputStream.readObject();
            System.out.println("反序列化成功");
            for (Student student : arrayList) {
                System.out.println(student);
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }
}
@AllArgsConstructor
@Data
class Student  implements Serializable {
      String name;
      String age;
}